package net.k3rnel.abugadro.gcodes;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.k3rnel.abugadro.ProjectsDB;
import net.k3rnel.abugadro.R;
import net.k3rnel.abugadro.Project.Projects;
import net.k3rnel.abugadro.gcodes.beans.Comment.Comments;
import net.k3rnel.abugadro.gcodes.beans.Issue.Issues;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.SyncService;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class BrowseIssue extends ListActivity implements AsyncQueryListener{

	public static final String TAG = "BrowseIssue";

	private CommentsAdapter mAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private int gcodeId;
	private int issueId;
	private final SyncService mSyncService = new SyncService();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gcode_issues_browse);

		final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		((TextView) findViewById(R.id.title_text)).setText(
				customTitle != null ? customTitle : getTitle());
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		final Uri issuesUri = getIntent().getData();
		gcodeId = Integer.parseInt(issuesUri.getPathSegments().get(1));
		issueId = Integer.parseInt(issuesUri.getPathSegments().get(3));
		if(!ProjectsDB.getInstance().isSyncedGcodeIssues(getContentResolver(),gcodeId,issueId))
			mSyncService.startThread(handler, getContentResolver(), issuesUri, 6);
		
		final ListView listView = getListView();
		final View view = getLayoutInflater().inflate(R.layout.list_issue_contents,
				listView, false);
		listView.addHeaderView(view, null, false);

		mAdapter = new CommentsAdapter(this);
		setListAdapter(mAdapter);

		final Uri commentsUri = Comments.buildFullUri(issuesUri.getPathSegments().get(1),issuesUri.getPathSegments().get(3));
		Log.i("Abugadro",commentsUri+"");
		mHandler.startQuery(1,null,issuesUri, IssuesQuery.PROJECTION,null,null,null);
		mHandler.startQuery(2,null,commentsUri, CommentsQuery.PROJECTION,Comments.GCODE_ID + " = " + commentsUri.getPathSegments().get(1)+ 
				" AND "+Comments.ISSUE_ID +" = "+commentsUri.getPathSegments().get(3),null,null);

	}

	@Override
	public boolean moveTaskToBack(boolean nonRoot) {
		mSyncService.stopThread();
		return super.moveTaskToBack(nonRoot);
	}
	private void displayAlert() {
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_alert).setVisibility(View.VISIBLE);
	}
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.getData().getInt("status")==1){
				updateRefreshStatus();
				final Uri projectUri = getIntent().getData();
				final Uri commentsUri = Comments.buildFullUri(projectUri.getPathSegments().get(1),projectUri.getPathSegments().get(3));
				mHandler.startQuery(2,null,commentsUri, CommentsQuery.PROJECTION,Comments.GCODE_ID + " = " + commentsUri.getPathSegments().get(1)+ 
						" AND "+Comments.ISSUE_ID +" = "+commentsUri.getPathSegments().get(3),null,null);
			}else
				displayAlert();

		}
	};
	private void updateRefreshStatus() {
		findViewById(R.id.gcode_home_btn_alert).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(
				mSyncService.isSync() ? View.GONE : View.VISIBLE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(
				mSyncService.isSync() ? View.VISIBLE : View.GONE);
	}
	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch(token){
		case 1:
			try {
				if (!cursor.moveToFirst()) return;
				((TextView) findViewById(R.id.gcode_title_entry)).setText(cursor.getString(IssuesQuery.ISSUE_ID)+" - "+ cursor.getString(IssuesQuery.TITLE));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_stars_entry)), "<b>"+cursor.getString(IssuesQuery.STARS)+" Stars</b>");
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_author_entry)),"<b>Reported by </b>"+ cursor.getString(IssuesQuery.AUTHOR));
				final TextView content = ((TextView) findViewById(R.id.gcode_summary_entry));
				content.setText(cursor.getString(IssuesQuery.CONTENT));
				UIUtils.setTextMaybeHtml(content, cursor.getString(IssuesQuery.CONTENT));
				Linkify.addLinks(content, Linkify.WEB_URLS);
				final String owner = cursor.getString(IssuesQuery.OWNER)+"";
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_owner_entry)), "<b>Owner:</b> " + (owner.equals("null") ? "---" : owner));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_status_entry)), "<b>Status:</b> " + cursor.getString(IssuesQuery.STATUS));
				String labels = "";
				labels = ProjectsDB.getInstance().getLabelsByIssueId(getContentResolver(),gcodeId,cursor.getInt(IssuesQuery.ISSUE_ID));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_labels_entry)), "<b>Labels:</b> " + labels);

				((TextView) findViewById(R.id.gcode_title_entry_empty)).setText(cursor.getString(IssuesQuery.ISSUE_ID)+" - "+ cursor.getString(IssuesQuery.TITLE));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_stars_entry_empty)), "<b>"+cursor.getString(IssuesQuery.STARS)+" Stars</b>");
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_author_entry_empty)),"<b>Reported by </b>"+ cursor.getString(IssuesQuery.AUTHOR));
				final TextView emptycontent = ((TextView) findViewById(R.id.gcode_summary_entry_empty));
				emptycontent.setText(cursor.getString(IssuesQuery.CONTENT));
				UIUtils.setTextMaybeHtml(emptycontent, cursor.getString(IssuesQuery.CONTENT));
				Linkify.addLinks(emptycontent, Linkify.WEB_URLS);
				final String emptyowner = cursor.getString(IssuesQuery.OWNER)+"";
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_owner_entry_empty)), "<b>Owner:</b> " + (emptyowner.equals("null") ? "---" : emptyowner));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_status_entry_empty)), "<b>Status:</b> " + cursor.getString(IssuesQuery.STATUS));
				labels = "";
				labels = ProjectsDB.getInstance().getLabelsByIssueId(getContentResolver(),gcodeId,cursor.getInt(IssuesQuery.ISSUE_ID));
				UIUtils.setTextMaybeHtml(((TextView) findViewById(R.id.gcode_labels_entry_empty)), "<b>Labels:</b> " + labels);
			}catch(Exception e){
				Log.e("Abugadro","GAH!",e);
			} finally {
				if(cursor!=null)
					cursor.close();
			}
			break;
		case 2:
			startManagingCursor(cursor);
			mAdapter.changeCursor(cursor);
			break;
		}
	}
	/** Handle "alert" title-bar action. */
	public void onAlertClick(View v) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Hold it!")
		.setMessage("No Internets. Will work with offline data")
		.create();
		ad.show();
		updateRefreshStatus();
	}
	/** Handle "home" title-bar action. */
	public void onAddClick(View v) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Sorry to dissapoint!")
		.setMessage("But I'm working on this.")
		.create();
		ad.show();
		/**
		 * 
		 
		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.dialog_add_comment, null);
		AlertDialog ad = new AlertDialog.Builder(this)
		.setTitle(R.string.gcode_comment_title)
		.setView(textEntryView)
		.setPositiveButton(R.string.option_add, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
//				String xml = 
//					"<entry xmlns='http://www.w3.org/2005/Atom' " +
//							"xmlns:issues='http://schemas.google.com/projecthosting/issues/2009'>"+
//					"<content type='html'>"+((EditText) findViewById(R.id.content_edit)).getText()+"</content>"+
//					"<author>"+
//					"<name>nushio</name>"+
//					"</author>"+
//					"</entry>";
//				List<NameValuePair> params = new ArrayList<NameValuePair>(2);
//				params.add(new BasicNameValuePair("application/atom+xml", xml));
//				params.add(new BasicNameValuePair("source", "Abugadro-v"+R.string.version));
//				HttpPost postRequest = new HttpPost("http://code.google.com/feeds/issues/p/"+projName+"/issues/"+issueId+"/comments/full");
//				postRequest.setEntity(new UrlEncodedFormEntity(params));
//				postRequest.setHeader("Authorization", "GoogleLogin auth=\""+auth+"\"");
//				HttpResponse response = new DefaultHttpClient().execute(postRequest);
//				if(response.getStatusLine().getStatusCode()==200){
//					HttpEntity entity = response.getEntity();
//					if(entity != null){
//						InputStream inputStream = entity.getContent();
//						auth = convertStreamToString(inputStream);
//						Log.i(TAG,auth);
//					}
//				}if(response.getStatusLine().getStatusCode()==201){
//					HttpEntity entity = response.getEntity();
//					if(entity != null){
//						InputStream inputStream = entity.getContent();
//						auth = convertStreamToString(inputStream);
//						Log.i(TAG,auth);
//					}
//				}else if(response.getStatusLine().getStatusCode()==403){
//					//Display bad password prompt
//					HttpEntity entity = response.getEntity();
//					if(entity != null){
//						InputStream inputStream = entity.getContent();
//						auth = convertStreamToString(inputStream);
//						Log.i(TAG,auth);
//					}
//
//					auth="forbidden";
//					createDialog("FYI","That Username/Password combination didn't work");
//				}else{
//					HttpEntity entity = response.getEntity();
//					if(entity != null){
//						InputStream inputStream = entity.getContent();
//						auth = convertStreamToString(inputStream);
//						Log.i(TAG,auth);
//					}
//
//					auth="forbidden";
//					createDialog("FYI","That Username/Password combination didn't work. \nError: "+response.getStatusLine().getStatusCode());
//				}
			}
		})
		.setNegativeButton(R.string.option_cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				// User clicked cancel so do some stuff 
			}
		})
		.create();
		ad.show();
		*/
	}
	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	/** Handle "refresh" title-bar action. */
	public void onRefreshClick(View v) {
		if(!mSyncService.isSync()){
			mSyncService.startThread(handler, getContentResolver(), getIntent().getData(), 6);
		}
	}
	/** {@link Projects} query parameters. */
	private interface IssuesQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Issues.ISSUE_ID,
				Issues.TITLE,
				Issues.CONTENT,
				Issues.AUTHOR,
				Issues.OWNER,
				Issues.STATUS,
				Issues.STARS,

		};
		//		int ID = 0;
		int ISSUE_ID = 1;
		int TITLE = 2;
		int CONTENT = 3;
		int AUTHOR = 4;
		int OWNER = 5;
		int STATUS = 6;
		int STARS = 7;
	}

	/**
	 * {@link CommentsAdapter} that renders a {@link CommentsQuery}.
	 */
	private class CommentsAdapter extends CursorAdapter {
		private LayoutInflater mInflater;

		public CommentsAdapter(Context context) {
			super(context, null);
			mInflater = LayoutInflater.from(context);
		}

		/** {@inheritDoc} */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			//			getListView().addHeaderView(findViewById(R.layout.list_issue_contents));
			return getLayoutInflater().inflate(R.layout.list_item_comment, parent, false);
		}

		/** {@inheritDoc} */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewHolder holder;
			if(view==null){
				view = mInflater.inflate(R.layout.list_item_comment, null);
				holder = new ViewHolder();
				holder.title = (TextView) view.findViewById(R.id.issue_title);
				holder.content = (TextView) view.findViewById(R.id.issue_content);
				holder.date = (TextView) view.findViewById(R.id.issue_date);
				holder.changes = (TextView) view.findViewById(R.id.issue_changes);

				view.setTag(holder);
			}else{
				holder = (ViewHolder) view.getTag();
			}

			holder.title.setText("#"+cursor.getString(CommentsQuery.COMMENT_ID)+" by "+cursor
					.getString(CommentsQuery.AUTHOR));   
			holder.content.setText(cursor.getString(CommentsQuery.CONTENT));
			Cursor miniCursor = ProjectsDB.getInstance().getIssueChangesByIssueId(getContentResolver(), gcodeId, issueId,cursor.getInt(CommentsQuery.COMMENT_ID));
			String tempChanges = "";
			while (null != miniCursor && miniCursor.moveToNext()) {
				String type = "";
				switch(miniCursor.getInt(1)){
				case 0:
					type = "Label";
					break;
				case 1:
					type = "Status";
					break;
				case 2:
					type = "CC";
					break;
				case 3:
					type = "Owner";
					break;
				default:
					type = "";
					break;
				}
				if(miniCursor.getString(2).equalsIgnoreCase("0"))
					tempChanges+="Added "+type+": "+miniCursor.getString(0)+"\n";
				else
					tempChanges+="Removed "+type+": "+miniCursor.getString(0)+"\n";
			}
			holder.changes.setText(tempChanges);
			miniCursor.close();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
			format.setTimeZone(java.util.TimeZone.getTimeZone("Zulu"));
			try {
				Date d = format.parse(cursor.getString(CommentsQuery.PUBLISHED));
				format.applyPattern("MMM, d ''yy 'at' HH:mma");
				holder.date.setText(format.format(d));
			} catch (ParseException e) {
				e.printStackTrace();
				holder.date.setText("");
			}
			Linkify.addLinks(holder.content,Linkify.WEB_URLS);
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView==null){
				convertView = mInflater.inflate(R.layout.list_item_comment, parent,false);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.issue_title);
				holder.content = (TextView) convertView.findViewById(R.id.issue_content);
				holder.date = (TextView) convertView.findViewById(R.id.issue_date);
				holder.changes = (TextView) convertView.findViewById(R.id.issue_changes);

				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			return super.getView(position, convertView, parent);
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}


	}
	static class ViewHolder {
		TextView title;
		TextView content;
		TextView date;
		TextView changes;
	}

	/** {@link Comments} query parameters. */
	private interface CommentsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Comments.COMMENT_ID,
				Comments.AUTHOR,
				Comments.TITLE,
				Comments.CONTENT,
				Comments.PUBLISHED,


		};
		int COMMENT_ID = 1;
		int AUTHOR = 2;
		//		int TITLE = 3;
		int CONTENT = 4;
		int PUBLISHED = 5;
	}
}